package org.cmy.config;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@Configuration
@Slf4j
public class TokenDebugFilterConfig {

    @Bean
    public OncePerRequestFilter tokenDebugFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                         FilterChain filterChain) throws ServletException, IOException {
                
                String path = request.getServletPath();
                
                // 只记录API请求
                if (path.startsWith("/api/")) {
                    String authHeader = request.getHeader("Authorization");
                    
                    if (authHeader != null && authHeader.startsWith("Bearer ")) {
                        String token = authHeader.substring(7);
                        
                        log.debug("=== TOKEN DEBUG INFO ===");
                        log.debug("Request URL: {} {}", request.getMethod(), request.getRequestURI());
                        log.debug("Token Present: Yes");
                        log.debug("Token Length: {}", token.length());
                        log.debug("Token Prefix: {}...", token.substring(0, Math.min(20, token.length())));
                        
                        // 记录所有headers（可选）
                        Enumeration<String> headerNames = request.getHeaderNames();
                        while (headerNames.hasMoreElements()) {
                            String headerName = headerNames.nextElement();
                            if (headerName.toLowerCase().contains("auth") || headerName.equals("Authorization")) {
                                log.debug("Header: {} = {}", headerName, request.getHeader(headerName));
                            }
                        }

                        log.debug("=========================");
                    } else {
                        log.debug("=== TOKEN DEBUG INFO ===");
                        log.debug("Request URL: {} {}", request.getMethod(), request.getRequestURI());
                        log.debug("Token Present: No");
                        log.debug("Authorization Header: {}", authHeader);
                        log.debug("=========================");
                    }
                }
                
                filterChain.doFilter(request, response);
            }
        };
    }
}